var pickerFile = require('../../../../../../../interest/lib/picker_datetime/js/picker_datetime.js');
const app = getApp()
const util = require('../../../../../../../utils/util.js');
const api = require('../../../../../../../config/api.js');
Page({
  data: {
    isHidePickerDatetime: true,// 是否隐藏优惠时间的选择
    contentType: "",
    index: "",
    themeAmountDetails: {},
    themeAmountDetailsAuxiliary: { "openDiscounts": false, "openCommission": false},
  },
  onLoad: function (options) {
    var _this = this;
    _this.datetimePicker = new pickerFile.pickerDatetime({
      page: _this,
      animation: 'slide',
      duration: 500
    });
    _this.setData({
      contentType: options.contentType,
      index: options.index,
      themeAmountDetails: JSON.parse(options.themeAmountDetails),
    })
    _this.initializePage();
  },

  /**
   * 初始化页面数据
   */
  initializePage: function(){
    var _this = this;
    var index = _this.data.index;
    if (index != null && String(index).length > 0 && parseInt(index) >= 0) {
      var themeAmountDetails = _this.data.themeAmountDetails;
      var preferentialSettings = _this.data.themeAmountDetails.preferentialSettings;
      var commission = _this.data.themeAmountDetails.commission;
      if (preferentialSettings != null && String(preferentialSettings).length > 0 && parseInt(preferentialSettings) > 0) {
        _this.setData({
          ["themeAmountDetailsAuxiliary.openDiscounts"]: true
        })
      }
      if (commission != null && String(commission).length > 0 && parseInt(commission) > 0) {
        _this.setData({
          ["themeAmountDetailsAuxiliary.openCommission"]: true
        })
      }
    }else{
      _this.setData({
        ["themeAmountDetails.designatedType"]: 0
      })
    }
  },

  /**
   * 获取输入的内容
   */
  inputValue: function(e){
    var _this = this
    var type = e.currentTarget.dataset.type;
    if (type =="name"){
      _this.setData({
        ["themeAmountDetails.name"]: e.detail.value.replace(/\s+/g, '')
      })
    }
    var value = parseInt(e.detail.value);
    value = value > 0 ? value : "";
    if (type == "price"){
      _this.setData({
        ["themeAmountDetails.price"]: value
      })
    }
    if (type =="cycleDays"){
      var designatedType = _this.data.themeAmountDetails.designatedType;
      if (designatedType == 2){
        _this.setData({
          ["themeAmountDetails.designatedDays"]: value
        })
      }
      
    }
    if (type =="number"){
      _this.setData({
        ["themeAmountDetails.numberPlaces"]: value
      })
    }
    if (type == "maxBuy") {
      _this.setData({
        ["themeAmountDetails.restrictionSetting"]: value
      })
    }
    if (type == "preferentialPrice"){
      _this.setData({
        ["themeAmountDetails.preferentialPrice"]: value
      })
    }
    if (type == "commissionPrice") {
      _this.setData({
        ["themeAmountDetails.commission"]: value
      })
    }
    if (type == "oneselfExtractPrice") {
      _this.setData({
        ["themeAmountDetails.packAmount"]: value
      })
    }
    if (type == "deliveryHomePrice") {
      _this.setData({
        ["themeAmountDetails.deliveryAmount"]: value
      })
    }
    if (type == "orangeShell") {
      _this.setData({
        ["themeAmountDetails.orangeShell"]: value
      })
    }
  },
  /**
   * 选项开关
   */
  switchChange: function(e){
    var _this = this
    var type = e.currentTarget.dataset.type;
    if (type =="discounts"){
      var preferentialSettings = _this.data.themeAmountDetails.preferentialSettings;
      preferentialSettings = preferentialSettings == null || String(preferentialSettings).length <= 0 || preferentialSettings == 0 ? 1 : preferentialSettings;
      _this.setData({
        ["themeAmountDetailsAuxiliary.openDiscounts"]: e.detail.value,
        ["themeAmountDetails.preferentialSettings"]: preferentialSettings,
      })
    }
    if (type == "commission") {
      _this.setData({
        ["themeAmountDetailsAuxiliary.openCommission"]: e.detail.value
      })
    }
    if (type == "oneselfExtract") {
      _this.setData({
        ["themeAmountDetails.isSelf"]: e.detail.value ? 1 : 0
      })
    }
    if (type == "deliveryHome") {
      _this.setData({
        ["themeAmountDetails.isDelivery"]: e.detail.value ? 1 : 0
      })
    }
  },
  /**
   * 选择周期类型
   */
  selecrCycleType: function (e) {
    var _this = this
    var index = e.currentTarget.dataset.index;
    _this.setData({
      ["themeAmountDetails.designatedType"]: index
    })
  },
  /**
   * 获取地址
   */
  getAddr: function(){
    var _this = this
    wx.getSetting({
      success(res) {
        console.log(res.authSetting)
        if (!res.authSetting['scope.userLocation']) {
          // 未授权
          wx.authorize({
            scope: 'scope.userLocation',
            success() {
              _this.diaryPositionStart();
            },
            fail: function () {
              // 拒绝授权
              _this.setData({
                addressOauhRefusedDialogShow: true
              })
            }
          })
        } else {
          // 已授权
          _this.diaryPositionStart();
        }
      }
    })
  },
  /**
  * 位置
  */
  diaryPositionStart: function () {
    var _this = this;
    wx.chooseLocation({
      success: function (res) {
        var name = res.name;
        var latitude = res.latitude;
        var longitude = res.longitude;
        var address = res.address;
        if (name.length > 0) {
          _this.setData({
            ["themeAmountDetails.detailedAddress"]: name,
            ["themeAmountDetails.latitude"]: String(latitude),
            ["themeAmountDetails.longitude"]: String(longitude),
            ["themeAmountDetails.address"]: address
          })
        }
      }
    })
  },
  /**
  * 优惠设置类型的改变
  */
  preferentialSettings: function (e) {
    var _this = this;
    var preferentialSettings = e.currentTarget.dataset.type;
    _this.setData({
      ["themeAmountDetails.preferentialSettings"]: preferentialSettings
    })
  },
  /**
   * 优惠开始时间
   */
  preferentialdateStart: function () {
    var _this = this;
    var preferentialdateStart = _this.data.themeAmountDetails.preferentialdateStart;
    if (preferentialdateStart == null || preferentialdateStart.length <= 0) {
      preferentialdateStart = util.haveSomeMinutesTime(60);
    }
    _this.datetimePicker.setPicker("themeAmountDetails.preferentialdateStart", preferentialdateStart);
    _this.setData({
      isHidePickerDatetime: false
    })
  },

  /**
   * 优惠结束时间
   */
  preferentialdateEnd: function () {
    var _this = this;
    var preferentialdateEnd = _this.data.themeAmountDetails.preferentialdateEnd;
    if (preferentialdateEnd == null || preferentialdateEnd.length <= 0) {
      preferentialdateEnd = util.haveSomeMinutesTime(120);
    }
    _this.datetimePicker.setPicker('themeAmountDetails.preferentialdateEnd', preferentialdateEnd);
    _this.setData({
      isHidePickerDatetime: false
    })
  },

  /**
   * 确定
   */
  submit: function(){
    var _this = this;
    if (_this.checkInfo()){
      // 校验通过，进行数据优化
      _this.optimizeData();
      var index = _this.data.index;
      var themeAmountDetails = _this.data.themeAmountDetails;
      var pages = getCurrentPages();
      var prevPage = pages[pages.length - 2];  //上一个页面
      var themeAmountDetailsList = prevPage.data.themeAmountDetailsList;
      if(index != null && String(index).length > 0 && parseInt(index) >= 0){
        prevPage.setData({
          ["themeAmountDetailsList[" + index + "]"]: themeAmountDetails
        });
      }else{
        themeAmountDetailsList.push(themeAmountDetails);
        prevPage.setData({
          ["themeAmountDetailsList"]: themeAmountDetailsList
        });
      }
      wx.navigateBack({
        delta: 1
      })
    }
  },

  /**
   * 校验信息
   */
  checkInfo: function(){
    var _this = this;
    var themeAmountDetails = _this.data.themeAmountDetails;
    var themeAmountDetailsAuxiliary = _this.data.themeAmountDetailsAuxiliary;
    var openDiscounts = themeAmountDetailsAuxiliary.openDiscounts;
    var openCommission = themeAmountDetailsAuxiliary.openCommission;

    var name = themeAmountDetails.name;
    var price = themeAmountDetails.price;
    var designatedType = themeAmountDetails.designatedType;
    var designatedDays = themeAmountDetails.designatedDays;
    var numberPlaces = themeAmountDetails.numberPlaces;
    var restrictionSetting = themeAmountDetails.restrictionSetting;
    var preferentialSettings = themeAmountDetails.preferentialSettings;
    var preferentialPrice = themeAmountDetails.preferentialPrice;
    var orangeShell = themeAmountDetails.orangeShell;
    var preferentialdateStart = themeAmountDetails.preferentialdateStart;
    var preferentialdateEnd = themeAmountDetails.preferentialdateEnd;
    var isSelf = themeAmountDetails.isSelf;
    var packAmount = themeAmountDetails.packAmount;
    var longitude = themeAmountDetails.longitude;
    var latitude = themeAmountDetails.latitude;
    var isDelivery = themeAmountDetails.isDelivery;
    var deliveryAmount = themeAmountDetails.deliveryAmount;
    var commission = themeAmountDetails.commission;
    if (name == null || String(name).length <= 0){
      util.showToast("请输入标签名称", "none");
      return false;
    }
    if (designatedType == null || String(designatedType).length <= 0) {
      _this.setData({
        ["themeAmountDetails.designatedType"]: 0
      })
    } else if (designatedType == 2 && (designatedDays == null || String(designatedDays).length <= 0 || parseInt(designatedDays) <= 0)){
      util.showToast("请输入费用周期天数", "none");
      return false;
    }
    if (openDiscounts){
      if (preferentialSettings == null || String(preferentialSettings).length <= 0) {
        _this.setData({
          ["themeAmountDetails.preferentialSettings"]: 1
        })
      }
      var preferentialText = "优惠";
      if (preferentialSettings == 2){
        preferentialText = "团购";
      } else if (preferentialSettings == 3){
        preferentialText = "橙贝";
      }
      if (preferentialPrice == null || String(preferentialPrice).length <= 0 || parseInt(preferentialPrice) <= 0) {
        util.showToast("请输入" + preferentialText+"价格", "none");
        return false;
      }
      if (preferentialSettings == 3 && (orangeShell == null || String(orangeShell).length <= 0 || parseInt(orangeShell) <= 0)){
        util.showToast("请输入橙贝数量", "none");
        return false;
      }
      if (preferentialdateStart == null || String(preferentialdateStart).length <= 0) {
        util.showToast("请输入" + preferentialText + "开始时间", "none");
        return false;
      }
      if (preferentialdateEnd == null || String(preferentialdateEnd).length <= 0) {
        util.showToast("请输入" + preferentialText + "结束时间", "none");
        return false;
      }
    }
    if (openCommission && (commission == null || String(commission).length <= 0 || parseInt(commission) <= 0)){
      util.showToast("请输入分销金额", "none");
      return false;
    }
    if (!_this.checkPrice()){
      return false;
    }
    if (isSelf != null && String(isSelf).length > 0 && parseInt(isSelf) == 1) {
      if (longitude == null || String(longitude).length <= 0 || latitude == null || String(latitude).length <= 0){
        util.showToast("请选择详细地址", "none");
        return false;
      }
    }
    return true;
  },

  /**
   * 优化数据
   */
  optimizeData: function(){
    var _this = this;
    var themeAmountDetails = _this.data.themeAmountDetails;
    var themeAmountDetailsAuxiliary = _this.data.themeAmountDetailsAuxiliary;
    var openDiscounts = themeAmountDetailsAuxiliary.openDiscounts;
    var openCommission = themeAmountDetailsAuxiliary.openCommission;
    var isSelf = themeAmountDetails.isSelf;
    var isDelivery = themeAmountDetails.isDelivery;
    if (!openDiscounts){
      _this.setData({
        ["themeAmountDetails.preferentialSettings"]: null,
        ["themeAmountDetails.preferentialPrice"]: null,
        ["themeAmountDetails.orangeShell"]: null,
        ["themeAmountDetails.preferentialdateStart"]: null,
        ["themeAmountDetails.preferentialdateEnd"]: null
      })
    }
    if (!openCommission){
      _this.setData({
        ["themeAmountDetails.commission"]: null,
      })
    }
    if (isSelf == null || parseInt(isSelf) != 1){
      _this.setData({
        ["themeAmountDetails.packAmount"]: null,
        ["themeAmountDetails.detailedAddress"]: null,
        ["themeAmountDetails.latitude"]: null,
        ["themeAmountDetails.longitude"]: null,
        ["themeAmountDetails.address"]: null
      })
    }
    if (isDelivery == null || parseInt(isDelivery) != 1){
      _this.setData({
        ["themeAmountDetails.deliveryAmount"]: null
      })
    }
  },

  /**
   * 校验价格
   */
  checkPrice: function () {
    var _this = this;
    var openDiscounts = _this.data.themeAmountDetailsAuxiliary.openDiscounts;
    var openCommission = _this.data.themeAmountDetailsAuxiliary.openCommission;
    var price = _this.data.themeAmountDetails.price;
    var preferentialSettings = _this.data.themeAmountDetails.preferentialSettings;
    var preferentialPrice = _this.data.themeAmountDetails.preferentialPrice;
    var commission = _this.data.themeAmountDetails.commission;
    var preferentialText = "优惠";
    if (preferentialSettings == 2) {
      preferentialText = "团购";
    } else if (preferentialSettings == 3) {
      preferentialText = "橙贝";
    }

    price = price == null || String(price).length <= 0 || parseInt(price) <= 0 ? 0 : price;
    if (price != null && String(price).length > 0 && parseInt(price) >= 0){
      // 校验优惠设置
      if (openDiscounts && preferentialPrice != null && String(preferentialPrice).length > 0 && parseInt(preferentialPrice) >= parseInt(price)){
        util.showToast(preferentialText+ "金额不能大于等于原价", "none");
        return false;
      }
      // 校验分销金额
      if (openCommission && commission != null && String(commission).length > 0) {
        if (openDiscounts && preferentialPrice != null && String(preferentialPrice).length > 0) {
          if (parseInt(commission) >= parseInt(preferentialPrice)) {
            util.showToast("分销金额不能大于等于" + preferentialText + "价格", "none");
            return false;
          }
        }
        if (parseInt(commission) >= parseInt(price)){
          util.showToast("分销金额不能大于等于原价", "none");
          return false;
        }
      }
    }
    return true;
  }
})